<?php
/**
 * This file belongs to huakaili project
 *
 * @author jszhang
 */
require_once ( 'AbstractDAO.php' );
class SearchDAO extends AbstractDAO {

    /**
     * insert user search information to database
     *
     * @param array $params
     */
    public function AddSearchHistory( $params ) {
        $ip = $params['user_ip'];
        $keyword = edp_db_input( trim($params['keyword']) );
	if( !empty($keyword) ){
        	//check keyword exist
	        $sql = "select * from search_history where keyword='$keyword'";
        	$result = $this->db->GetRow( $sql );
	        if( !empty($keyword) && $result==false ) {
        	    $sql = "insert into search_history (`user_ip`, `keyword`, `date`) values ('$ip','$keyword', NOW())";
	            $this->db->Insert( $sql );
       		}
        	else {
            		$sql = "update search_history set `user_ip`='$ip', `count`=count+1, `date`=NOW() where keyword='$keyword'";
            		$this->db->Update( $sql );
        	}
	}
    }

    /**
     * get user search suggestions
     *
     * @param string $keyword
     */
    public function GetSuggestions( $keyword ) {
        $result = array();
        if( !empty($keyword) && $result==false ) {
            $keyword = edp_db_input( $keyword );
            $sql = "select keyword from search_history where keyword like '%$keyword%' and keyword!='$keyword' order by count desc";
            $result = $this->getRows($sql, SEARCH_SUGGESTION_PAGE);
        }

        return $result;
    }
    
    public function GetPopularSearch()
    {
    	$sql = 'select keyword
			    from search_history sh
			    inner join (select id from search_history order by count desc limit 10) jt
			    on sh.id = jt.id';
		
		return $this->db->GetPlan( $sql, true, CNS_INDEX, 'getPopularSearch' );
    }
}
?>
